#include "rcrypt.h"
#include "aes.h"

#include <stdio.h>

#ifdef _WIN32
#include <Windows.h>
#endif

#define ENCRYPT_KEY {\
		0x89C04244, 0xAC5C4E74, 0x93C53DBC, 0x204B4A91 \
	}

void print_data(const uint8_t* data,int len) {
	printf("data:");
	for (int i = 0; i < len; ++i) {
		printf("%d ", (int)data[i]);
	}
	printf("\n");
}

#define TEST_DATA_LEN 1024

void rcrypt_benchmark() {
	uint32_t key[] = ENCRYPT_KEY;
	uint8_t *buf = malloc(TEST_DATA_LEN + 16);
	uint8_t  head[4];
	for (int i = 0; i < 10000; ++i) {
		int len = rcrypt_encrypt(head, buf, TEST_DATA_LEN, key);
		len = rcrypt_decrypt(head, buf, len, key);
	}
	free(buf);
}

void aes_benchmark() {
	uint32_t key[] = ENCRYPT_KEY;
	uint8_t *buf = malloc(TEST_DATA_LEN + 16);
	aes_context aes;
	aes_set_key(&aes, (uint8_t*)key, sizeof(key) * 8);

	for (int i = 0; i < 10000; ++i) {
		for (int j = 0; j < TEST_DATA_LEN;) {
			aes_encrypt(&aes, buf, buf);
			aes_decrypt(&aes, buf, buf);
			j += 16;
		}
	}
	free(buf);
}


int main(const char* argv[], int argc) {

	uint32_t key[] = ENCRYPT_KEY;
	DWORD time = GetTickCount();

	rcrypt_benchmark();

	printf("tea_benchmark cost %d\n", GetTickCount() - time);
	time = GetTickCount();
	aes_benchmark();
	printf("aes_benchmark cost %d\n", GetTickCount() - time);


	for (int i = 0; i < 1000; ++i) 
	{
		uint8_t *data = malloc(i+16);
		uint8_t  head[4];

		for (int j = 0; j < i; ++j) {
			data[j] = j;
		}

		int len = rcrypt_encrypt(head, data, i, key);
		len = rcrypt_decrypt(head, data, len, key);

		if (len != i) {
			printf("len error %d!=%d\n", len, i);
			free(data);
			return -1;
		}

		for (int j = 0; j < i; ++j) {
			if (data[j] != j%256) {
				print_data(data, len);
				printf("error %d!=%d\n", data[j],j);
				free(data);
				return -1;
			}
		}
		free(data);
	}

	printf("test ok\n");
	getchar();
	return 0;
}
